package com.link2room.rodimus.handler.impl;

import com.link2room.common.service.ICommonService;
import com.link2room.rodimus.dto.param.base.SignInReissueHandlerParamDto;
import com.link2room.rodimus.entity.SignInReissueBaseEntity;
import com.link2room.rodimus.entity.SignInReissueDetailResvEntity;
import com.link2room.rodimus.handler.ISignInDrawReissueHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * Created by LN on 2018/1/10
 */
@Component("signInDrawReissueResvHandler")
public class SignInDrawReissueResvHandler extends AbstractSignInDrawReissueHandler  implements ISignInDrawReissueHandler {
    @Autowired
    private RedisLockRegistry signReissueLcok;
    @Resource
    private ICommonService commonService;


    @Override
    @Transactional
    public void signInReissue(String type ,SignInReissueHandlerParamDto paramDto) throws Exception {
        String l2rNo = paramDto.getL2rNo();
        String memberNo = paramDto.getMemberNo();
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        Date month = paramDto.getMonth();
        Integer value = paramDto.getValue();
        Lock lock = signReissueLcok.obtain(memberNo);

        if(lock.tryLock(30, TimeUnit.SECONDS)){
            try{
                SignInReissueDetailResvEntity findResvEntity = new SignInReissueDetailResvEntity();
                findResvEntity.setMemberNo(memberNo);
                findResvEntity.setLhotelGroupCode(lhotelGroupCode);
                findResvEntity.setOrderNo(l2rNo);
                findResvEntity.setMonth(month);
                commonService.save(findResvEntity);


                SignInReissueBaseEntity findReissueBase = new SignInReissueBaseEntity();
                findReissueBase.setMemberNo(memberNo);
                findReissueBase.setMonth(month);
                findReissueBase.setLhotelGroupCode(lhotelGroupCode);
                SignInReissueBaseEntity reissueBase = commonService.findOneEQ(SignInReissueBaseEntity.class, findReissueBase);
                if(reissueBase == null){
                    findReissueBase.setTotal(1);
                    findReissueBase.setUsed(0);
                    reissueBase = findReissueBase;
                }else {
                    reissueBase.setTotal(reissueBase.getTotal() + value);
                }
                commonService.save(reissueBase);
            }finally {
                lock.unlock();
            }
        }
    }


}
